package com.ky.tms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ky.tms.entity.*;
import com.ky.tms.enums.OrderEnum;
import com.ky.tms.exception.PredictableException;
import com.ky.tms.mapper.TmsCustomerMapper;
import com.ky.tms.mapper.TmsInvoiceMapper;
import com.ky.tms.mapper.TmsInvoiceOrderMapper;
import com.ky.tms.mapper.TmsOrderMapper;
import com.ky.tms.service.ITmsInvoiceService;
import com.ky.tms.vo.InvoiceOrders;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chengkaimao
 * @since 2020-04-22
 */
@Service
public class TmsInvoiceServiceImpl extends ServiceImpl<TmsInvoiceMapper, TmsInvoice> implements ITmsInvoiceService {

    @Autowired
    private TmsCustomerMapper tmsCustomerMapper;

    @Autowired
    private TmsOrderMapper tmsOrderMapper;

    @Autowired
    private TmsInvoiceMapper tmsInvoiceMapper;

    @Autowired
    private TmsInvoiceOrderMapper tmsInvoiceOrderMapper;

    @Override
    public IPage<TmsInvoice> gatheringPage(String userName, TmsInvoice tmsInvoice, Long limit, Long pages) {
        IPage<TmsInvoice> page = new Page(pages,limit);
        QueryWrapper<TmsInvoice> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(tmsInvoice.getInvoiceNo())){
            wrapper.like("invoice_no", tmsInvoice.getInvoiceNo());
        }
        if(tmsInvoice.getIsLock() != null){
            wrapper.eq("is_lock", tmsInvoice.getIsLock());
        }
        wrapper.eq("is_valid", 1);
        //wrapper.eq("is_lock", 0);
        wrapper.orderByDesc("create_time");
        page = this.page(page, wrapper);
        return page;
    }

    @Override
    public IPage<TmsInvoice> invoiceReportPage(String userName, TmsInvoice tmsInvoice, Long limit, Long pages) {
        IPage<TmsInvoice> page = new Page(pages, limit);
        List<TmsInvoice> tmsInvoices = tmsInvoiceMapper.invoiceReportPage(page, tmsInvoice);
        for(TmsInvoice invoice : tmsInvoices){
            Long id = invoice.getId();
            invoice.setOrders(tmsInvoiceMapper.selectOrders(id));
        }
        page.setRecords(tmsInvoices);
        return page;
    }

    @Override
    public String checkInvoice(List<TmsOrder> orders) throws PredictableException {

        HashSet<Long> longHashSet = new HashSet<>();
        for(TmsOrder order : orders){
            if(order.getCustomId() == null){
                throw new PredictableException("客户不能为空");
            }
            longHashSet.add(order.getCustomId());
        }
        if(longHashSet.size()>1){
            throw new PredictableException("不同客户不能开票");
        }
        TmsCustomer tmsCustomer = tmsCustomerMapper.selectById(longHashSet.iterator().next());
        return tmsCustomer.getInvoiceInfo();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void invoice(String userName, InvoiceOrders invoiceOrders) throws PredictableException {
        LocalDateTime now = LocalDateTime.now();
        TmsInvoice tmsInvoice = invoiceOrders.getTmsInvoice();
        List<TmsOrder> orders = invoiceOrders.getOrders();
        List<Long> ids = new ArrayList<>();
        BigDecimal sum = new BigDecimal("0.00");
        for(TmsOrder order : orders){
            ids.add(order.getId());
            // TODO
            sum = sum.add(order.getFeeSum());
        }

        if(sum.compareTo(tmsInvoice.getInvoiceAmount()) == -1){
            throw new PredictableException("开票金额大于实际收入！");
        }
        QueryWrapper<TmsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        queryWrapper.eq("is_valid", 1);
        queryWrapper.notIn("status", new String[]{OrderEnum.GATHERING.getValue(), OrderEnum.INVOICE_HALF.getValue()});
        // queryWrapper.and(wrapper-> wrapper.ne("status", OrderEnum.GATHERING.getValue()).or().ne("status", OrderEnum.INVOICE_HALF.getValue()));
        List<TmsOrder> tmsOrders = tmsOrderMapper.selectList(queryWrapper);
        if(tmsOrders.size() > 1){
            throw new PredictableException("状态异常！");
        }
        tmsInvoice.setCreateTime(now);
        tmsInvoice.setCreateUser(userName);
        tmsInvoice.setIsValid(1);
        tmsInvoice.setIsLock(0);
        tmsInvoiceMapper.insert(tmsInvoice);
        for(TmsOrder order : orders){
            TmsInvoiceOrder tmsInvoiceOrder = new TmsInvoiceOrder();
            tmsInvoiceOrder.setOrderId(order.getId());
            tmsInvoiceOrder.setInvoiceId(tmsInvoice.getId());
            tmsInvoiceOrder.setIsValid(1);
            tmsInvoiceOrderMapper.insert(tmsInvoiceOrder);
        }
        QueryWrapper<TmsOrder> upWrapper = new QueryWrapper<>();
        upWrapper.in("id", ids);
        upWrapper.eq("is_valid", 1);
        TmsOrder order = new TmsOrder();
        order.setStatus(tmsInvoice.getIsFull());
        tmsOrderMapper.update(order,upWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void gathering(String userName, TmsInvoice tmsInvoice) throws PredictableException {
        LocalDateTime now = LocalDateTime.now();
        tmsInvoice.setUpdateTime(now);
        tmsInvoice.setUpdateUser(userName);
        int gathering = tmsInvoiceMapper.gathering(tmsInvoice);
        if(gathering != 1){
            throw new PredictableException("收款失败！");
        }
        if(OrderEnum.FINISH.getValue().equals(tmsInvoice.getIsPayFull())){
            QueryWrapper<TmsInvoiceOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("invoice_id", tmsInvoice.getId());
            wrapper.eq("is_valid", 1);
            List<TmsInvoiceOrder> tmsInvoiceOrders = tmsInvoiceOrderMapper.selectList(wrapper);
            List<Long>  ids = new ArrayList<>();
            for(TmsInvoiceOrder tmsInvoiceOrder : tmsInvoiceOrders){
                ids.add(tmsInvoiceOrder.getOrderId());
            }

            QueryWrapper<TmsOrder> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", ids);
            queryWrapper.eq("is_valid", 1);
            queryWrapper.notIn("status", new String[]{OrderEnum.INVOICE.getValue()});
            List<TmsOrder> tmsOrders = tmsOrderMapper.selectList(queryWrapper);
            if(tmsOrders.size() > 1){
                throw new PredictableException("状态异常！");
            }

            TmsOrder order = new TmsOrder();
            order.setStatus(OrderEnum.FINISH.getValue());
            QueryWrapper<TmsOrder> upWrapper = new QueryWrapper<>();
            upWrapper.in("id", ids);
            upWrapper.eq("is_valid", 1);
            tmsOrderMapper.update(order, upWrapper);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirm(String userName, TmsInvoice tmsInvoice) throws PredictableException {
        LocalDateTime now = LocalDateTime.now();
        tmsInvoice.setUpdateUser(userName);
        tmsInvoice.setUpdateTime(now);
        tmsInvoice.setIsLock(1);
        tmsInvoiceMapper.updateById(tmsInvoice);

        QueryWrapper<TmsInvoiceOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("invoice_id", tmsInvoice.getId());
        wrapper.eq("is_valid", 1);
        List<TmsInvoiceOrder> tmsInvoiceOrders = tmsInvoiceOrderMapper.selectList(wrapper);
        List<Long>  ids = new ArrayList<>();
        for(TmsInvoiceOrder tmsInvoiceOrder : tmsInvoiceOrders){
            ids.add(tmsInvoiceOrder.getOrderId());
        }

        QueryWrapper<TmsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        queryWrapper.eq("is_valid", 1);
        queryWrapper.notIn("status", new String[]{OrderEnum.INVOICE.getValue()});
        List<TmsOrder> tmsOrders = tmsOrderMapper.selectList(queryWrapper);
        if(tmsOrders.size() > 1){
            throw new PredictableException("状态异常！");
        }

        TmsOrder order = new TmsOrder();
        order.setStatus(OrderEnum.FINISH.getValue());
        QueryWrapper<TmsOrder> upWrapper = new QueryWrapper<>();
        upWrapper.in("id", ids);
        upWrapper.eq("is_valid", 1);
        tmsOrderMapper.update(order, upWrapper);


    }


}
